<script lang="ts" setup>
  import { ref, watch } from 'vue'
  import UpdateNetworkForm from './UpdateNetworkForm.vue'
  import { ElMessage } from 'element-plus'
  import { useRouter } from 'vue-router'

  const props = defineProps<{
    network: string
    networkId: string
    orderId: string
    modelValue: boolean
    address: {
      province: string
      city: string
      area: string
      town: string
    }
  }>()

  const emits = defineEmits<{
    (e: 'update'): void
    (e: 'update:modelValue', value: boolean): void
  }>()

  const visible = ref(false)
  const router = useRouter()
  const updateNetworkFormInstance = ref<InstanceType<typeof UpdateNetworkForm> | null>(null)

  const onSave = async () => {
    if (updateNetworkFormInstance.value) {
      try {
        const res = await updateNetworkFormInstance.value.save()
        ElMessage({
          type: res.success ? 'success' : 'error',
          message: res.message,
          duration: 5000,
          plain: true,
          showClose: true,
        })

        if (res.success) {
          visible.value = false
          emits('update')
          emits('update:modelValue', visible.value)
        }
      } catch (error) {
        // 切不可删除该注释，否则会引起eslint报错
        // 也不可删除catch块，否则会引起控制台报错
      }
    }
  }

  const onCancel = () => {
    if (updateNetworkFormInstance.value) {
      updateNetworkFormInstance.value.resetForm()
      visible.value = false
      emits('update:modelValue', false)
    }
  }

  const onAddNetwork = () => {
    onCancel()
    router.push({ path: '/net/new' })
  }

  watch(
    () => props.modelValue,
    (value) => {
      visible.value = value
    },
    { immediate: true },
  )
</script>

<template>
  <h-dialog
    v-model="visible"
    :loading="updateNetworkFormInstance && updateNetworkFormInstance.saveLoading"
    title="改派部门"
    @close="onCancel"
  >
    <div class="update_network_modal_content">
      <div class="title">
        <i class="iconfont icon-warning"></i>
        <span class="text">改派后，该工单不再属于原部门</span>
      </div>
      <update-network-form
        ref="updateNetworkFormInstance"
        :address="props.address"
        :network="props.network"
        :network-id="props.networkId"
        :order-id="props.orderId"
        @add-network="onAddNetwork"
      />
    </div>

    <!-- 按钮组 -->
    <template #footer>
      <h-button is-modal type="primary" @click="onSave">保存</h-button>
      <h-button is-modal @click="onCancel">取消</h-button>
    </template>
  </h-dialog>
</template>

<style lang="scss" scoped>
  .update_network_modal_content {
    display: flex;
    flex-direction: column;
    row-gap: 14px;

    .title {
      display: flex;
      gap: 5px;

      .iconfont {
        color: $primaryColor;
        font-size: 18px;
      }

      .text {
        font-size: 14px;
        line-height: 16px;
      }
    }
  }
</style>
